package cn.tedu.spring_security.service;

import cn.tedu.spring_security.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;

public class UserDetailsImpl implements UserDetails {
    private User user;

    public UserDetailsImpl(User user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //将User的角色信息， 翻译为SpringSecurity的角色信息
        String[] roles = user.getRoles().split(",");
        ArrayList<GrantedAuthority> list = new ArrayList<>();
        for (String role : roles) {
            SimpleGrantedAuthority authority =
                    new SimpleGrantedAuthority("ROLE_" + role);
            list.add(authority);
        }
        return list;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}